import React from 'react';
import emitter from '../../utils/events';
import { globalThemeGroup } from '../index';

export const useGetThemeData = () => {
  const [themeData, setThemeData] = React.useState({
    key: null,
    enums: {},
  });

  React.useLayoutEffect(() => {
    const localThemeKey = window.localStorage.getItem('saas-theme') || 'light';
    const globalThemeData = globalThemeGroup[localThemeKey];
    setThemeData({ ...globalThemeData });
    // theme监听
    emitter.addListener('onGlobalThemeChange', (e) => onGlobalThemeListener(e));
    return () => {
      emitter.removeListener('onGlobalThemeChange', onGlobalThemeListener);
    };
  }, []);

  const onGlobalThemeListener = ({ key, enums }) => {
    if (key !== themeData.key) {
      setThemeData({
        key,
        enums,
      });
    }
  };
  return themeData;
};
